#include "formmemberandteam.h"
#include "ui_formmemberandteam.h"
#include <QSqlRelationalDelegate>
#include <QDebug>
#include <QSqlQueryModel>
#include <QSqlError>
#include <QMessageBox>
#include <QDateEdit>

FormMemberAndTeam::FormMemberAndTeam(QSqlDatabase db, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormMemberAndTeam),
    dbase(db),
    modelMember(new QSqlRelationalTableModel(this, dbase)),
    modelRange(new QSqlTableModel(this, dbase)),
    modelgender(new QSqlTableModel(this, dbase)),
    viewRange(new QTableView()),
    viewgender(new QTableView()),
    modelTeam(new teamMemberModel(dbase, this))
{
    ui->setupUi(this);

    QAction *actionSeparate = new QAction(this);
    actionSeparate->setSeparator(true);

    ui->toolButtonInsertToTeam->setIcon(QIcon::fromTheme("go-next"));
    ui->toolButtonInsertToTeam->setToolTip(tr("Include to team"));
    ui->toolButtonDropFromTeam->setIcon(QIcon::fromTheme("go-previous"));
    ui->toolButtonDropFromTeam->setToolTip(tr("Exclude from team"));
    ui->labelFind->setPixmap(QIcon::fromTheme("edit-find-user").pixmap(22, 22));

    ui->tableViewMember->setContextMenuPolicy(Qt::ActionsContextMenu);
    ui->tableViewMember->addAction(ui->actionAdd_member);
    ui->actionAdd_member->setIcon(QIcon::fromTheme("list-add-user"));
    ui->tableViewMember->addAction(ui->actionDrop_member);
    ui->actionDrop_member->setIcon(QIcon::fromTheme("list-remove-user"));
    ui->tableViewMember->addAction(actionSeparate);
    ui->tableViewMember->addAction(ui->actionMemberUpdate);
    ui->actionMemberUpdate->setIcon(QIcon::fromTheme("document-revert"));
    ui->tableViewMember->addAction(ui->actionMemberCommit);
    ui->actionMemberCommit->setIcon(QIcon::fromTheme("dialog-ok-apply"));

    ui->tableViewMember->setSelectionMode(QTableView::SingleSelection);
    ui->tableViewMember->setSelectionBehavior(QTableView::SelectRows);

    ui->treeViewTeam->setSelectionMode(QTableView::SingleSelection);
    ui->treeViewTeam->setSelectionBehavior(QTableView::SelectRows);

    ui->treeViewTeam->setContextMenuPolicy(Qt::ActionsContextMenu);
    ui->treeViewTeam->addAction(ui->actionAdd_team);
    ui->actionAdd_team->setIcon(QIcon::fromTheme("user-group-new"));
    ui->treeViewTeam->addAction(ui->actionDrop_team);
    ui->actionDrop_team->setIcon(QIcon::fromTheme("user-group-delete"));
    ui->treeViewTeam->addAction(actionSeparate);
    ui->treeViewTeam->addAction(ui->actionTeamUpdate);
    ui->actionTeamUpdate->setIcon(QIcon::fromTheme("document-revert"));
    ui->treeViewTeam->addAction(ui->actionTeamCommit);
    ui->actionTeamCommit->setIcon(QIcon::fromTheme("dialog-ok-apply"));


    ui->pushButtonApply->setIcon(QIcon::fromTheme("dialog-ok-apply"));
    ui->pushButtonReject->setIcon(QIcon::fromTheme("dialog-cancel"));
    ui->pushButtonReload->setIcon(QIcon::fromTheme("document-revert"));

    setWindowTitle(tr("Member and team base"));

    connect(ui->tableViewMember, SIGNAL(clicked(QModelIndex)), ui->tableViewMember, SLOT(edit(QModelIndex)));
    connect(ui->treeViewTeam, SIGNAL(clicked(QModelIndex)), ui->treeViewTeam, SLOT(edit(QModelIndex)));
}

FormMemberAndTeam::~FormMemberAndTeam()
{
    delete ui;
}

void FormMemberAndTeam::showEvent(QShowEvent *e)
{
    e->accept();
    ui->tableViewMember->setColumnWidth(1,200);
    ui->treeViewTeam->setColumnWidth(1,150);
    ui->treeViewTeam->setColumnWidth(2,250);
    ui->treeViewTeam->expandAll();
}

void FormMemberAndTeam::on_actionAdd_member_triggered()
{
    int memberId = 1;
    modelMember->insertRow(modelMember->rowCount());
    for (int id = 0; id != modelMember->rowCount(); id++) {
        if (memberId <= modelMember->data(modelMember->index(id, 0)).toInt()) memberId = modelMember->data(modelMember->index(id, 0)).toInt()+1;
    }
    modelMember->setData(modelMember->index(modelMember->rowCount()-1,0), memberId);
}

void FormMemberAndTeam::on_actionAdd_team_triggered()
{
    modelTeam->insertRow(modelTeam->rowCount());
    ui->treeViewTeam->setCurrentIndex(modelTeam->index(modelTeam->rowCount()-1, 0));
}

void FormMemberAndTeam::on_actionDrop_team_triggered()
{
    if (ui->treeViewTeam->currentIndex().isValid()) modelTeam->removeRow(ui->treeViewTeam->currentIndex().row());
}

void FormMemberAndTeam::MemberUpdate()
{
    modelMember->setTable("member");
    modelMember->setRelation(3, QSqlRelation("sport_range","id","title"));
    modelMember->setRelation(4, QSqlRelation("gender_member","id","title"));
    modelMember->setHeaderData(1, Qt::Horizontal, tr("member"));
    modelMember->setHeaderData(2, Qt::Horizontal, tr("dob"));
    modelMember->setHeaderData(3, Qt::Horizontal, tr("range"));
    modelMember->setHeaderData(4, Qt::Horizontal, tr("gender"));

    modelRange->setTable("sport_range");
    viewRange->setModel(modelRange);

    modelgender->setTable("gender_member");
    viewgender->setModel(modelgender);

    ui->tableViewMember->setModel(modelMember);
    ui->tableViewMember->hideColumn(0);
    /// @todo Edit delegate for dob
    ui->tableViewMember->setItemDelegateForColumn(2, new QItemDelegate(new QDateEdit()));
    ui->tableViewMember->setItemDelegateForColumn(3, new QSqlRelationalDelegate(viewRange));
    ui->tableViewMember->setItemDelegateForColumn(4, new QSqlRelationalDelegate(viewgender));

    modelMember->setEditStrategy(QSqlTableModel::OnManualSubmit);
    modelMember->setSort(1, Qt::AscendingOrder);

    modelMember->select();
}

void FormMemberAndTeam::TeamUpdate()
{
    ui->treeViewTeam->setModel(modelTeam);
    ui->treeViewTeam->hideColumn(1);
    ui->treeViewTeam->hideColumn(4);

    modelTeam->select();
    ui->treeViewTeam->setColumnWidth(0, 250);
    ui->treeViewTeam->setColumnWidth(2, 150);
    ui->treeViewTeam->setColumnWidth(3, 35);
    ui->treeViewTeam->setRootIsDecorated(true);
    ui->treeViewTeam->show();
    ui->treeViewTeam->expandAll();
}

void FormMemberAndTeam::on_actionDrop_member_triggered()
{
    if (ui->tableViewMember->currentIndex().isValid()) modelMember->removeRow(ui->tableViewMember->currentIndex().row());
}

void FormMemberAndTeam::on_lineEdit_textChanged(const QString &arg1)
{
    qDebug() << tr("Find function not implicted");
}

void FormMemberAndTeam::on_tableViewMember_clicked(const QModelIndex &index)
{
    ui->toolButtonInsertToTeam->setEnabled(index.isValid());
    ui->actionDrop_member->setEnabled(index.isValid());
}

void FormMemberAndTeam::on_actionMemberUpdate_triggered()
{
    TeamUpdate();
    MemberUpdate();
}

void FormMemberAndTeam::on_actionMemberCommit_triggered()
{
    modelMember->submitAll();
    if (modelMember->lastError().type() == QSqlError::NoError) {
        modelMember->select();
    } else {
        QMessageBox::critical(this, tr("SQL transaction error"),
                              tr("Error detail : ") + modelMember->lastError().driverText() + "<br/>",
                              QMessageBox::Close, QMessageBox::Close);
    }
}

void FormMemberAndTeam::on_pushButtonReload_clicked()
{
    TeamUpdate();
    MemberUpdate();
}

void FormMemberAndTeam::on_pushButtonReject_clicked()
{
    close();
    emit closed();
}

void FormMemberAndTeam::on_pushButtonApply_clicked()
{
    modelMember->submitAll();
    if (modelMember->lastError().type() == QSqlError::NoError) {
        modelMember->select();

        close();
        emit closed();
    } else {
        QMessageBox::critical(this, tr("SQL transaction error"), tr("Members table") + "<br/>" +
                              tr("Error detail : ") + modelMember->lastError().driverText() + "<br/>",
                              QMessageBox::Close, QMessageBox::Close);
    }
}

void FormMemberAndTeam::on_actionTeamCommit_triggered()
{
    modelTeam->submitManual();
    ui->treeViewTeam->expandAll();
}

void FormMemberAndTeam::on_actionTeamUpdate_triggered()
{
    TeamUpdate();
}

void FormMemberAndTeam::on_toolButtonInsertToTeam_clicked()
{
    /// @todo insert test to inclede member to other teams

    if (ui->tableViewMember->currentIndex().isValid() && ui->treeViewTeam->currentIndex().isValid()) {
        modelTeam->addChild(ui->treeViewTeam->currentIndex(),
                            modelMember->data(modelMember->index(ui->tableViewMember->currentIndex().row(),1)).toString(),
                            modelMember->data(modelMember->index(ui->tableViewMember->currentIndex().row(),0)).toInt());
    } else {
        QMessageBox::critical(this, windowTitle(),
                              tr("Must be selected team and member"),
                              QMessageBox::Close, QMessageBox::Close);
    }
}

void FormMemberAndTeam::on_toolButtonDropFromTeam_clicked()
{
    if (ui->treeViewTeam->currentIndex().isValid()) {
            modelTeam->dropChild(ui->treeViewTeam->currentIndex());
    }
}
